package com.avic.rong.utils;


import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class PasswordUtil {

    public static final String getMD5(String text) {

        byte[] intext = text.getBytes();
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] md5rslt = md5.digest(intext);
        StringBuffer verifyMsg = new StringBuffer();
        for (int i = 0; i < md5rslt.length; i++) {
            int hexChar = 0xFF & md5rslt[i];
            String hexString = Integer.toHexString(hexChar);
            hexString = (hexString.length() == 1) ? "0" + hexString : hexString;
            verifyMsg.append(hexString);
        }
        return verifyMsg.toString().toLowerCase();
    }


    public static String getStringMD5(String string, String salt) throws NoSuchAlgorithmException {

        String target = null;
        if (TextUtils.isEmpty(salt)) {
            target = string;
        } else {
            target = getStringMD5(salt + string + salt, null);
        }

        byte[] byteString = target.getBytes(Charset.forName("utf-8"));
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(byteString);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString();
    }


    public static String getFileMD5(String filePath) throws NoSuchAlgorithmException, IOException, DigestException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        int length = 0;
        byte[] buffer = new byte[1024];
        byte[] array = null;
        InputStream is = new FileInputStream(new File(filePath));
        while ((length = is.read(buffer)) != -1) {
            md.update(buffer, 0, length);
        }

        is.close();

        array = md.digest();

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
        }

        return sb.toString();
    }
}
